import { Button, Checkbox, Form, Input, message } from 'antd';
import Cookies from 'js-cookie';
import React, { useState } from 'react';
import { history, useDispatch } from 'umi';

import type { Dispatch } from 'umi';

import { namespace } from '@/models/global';
import ForgetPassCode from '@/pages/Login/UserLogin/ForgetPassCode';
import { resetPasswordByPhoneNo } from '@/services/login';
import { getErrorMsg } from '@/util/utils';

import wechatPic from '../../../assets/images/wechat.png';
import styles from '../MsnLogin/index.less';

interface Props {
  switchMsnOrUser: (arg0: number) => void;
}
const UserLogin: React.FC<Props> = (props: Props) => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isAutoLogin, setIsAutoLogin] = useState(false);
  const [loginLoading, setLoginLoading] = useState(false);
  const dispatch = useDispatch<Dispatch>();
  const autoLogin = (e: any) => {
    setIsAutoLogin(e.target.checked);
  };
  const onFinish = (values: any) => {
    setLoginLoading(true);
    dispatch({
      type: `${namespace}/login`,
      payload: values,
      callback: (res: any) => {
        const { code, data } = res;
        if (code && code === 200) {
          setLoginLoading(false);
          if (!isAutoLogin) {
            Cookies.set('saas_token', 'Bearer ' + data.token);
            Cookies.set('isAutoLogin', 'false');
          } else {
            Cookies.set('saas_token', 'Bearer ' + data.token, { expires: data.expire / 86400 });
            Cookies.set('isAutoLogin', 'true');
          }
          message.success('登录成功!');
          dispatch({
            type: `${namespace}/getUserInfo`,
            callback() {
              history.push('/');
            },
          });
        } else {
          message.error(getErrorMsg(res));
          setLoginLoading(false);
        }
      },
      callbackLoading() {
        setLoginLoading(false);
      },
    });
  };
  const loginWithMsn = () => {
    return message.info('暂未开放');
    console.log('用户登录');
    props.switchMsnOrUser(1);
  };
  const loginWithWechat = () => {
    return message.info('暂未开放');
    console.log('二维码登录');
    props.switchMsnOrUser(2);
  };
  const forgetPassCode = () => {
    setIsModalVisible(true);
  };
  const handleOk = async (forgetPsdFormBean: any) => {
    const value =  forgetPsdFormBean.getFieldsValue();
    forgetPsdFormBean.validateFields().then(async () => {
      const res = await resetPasswordByPhoneNo(value);
      if (res.code === 200){
        message.success('修改成功!请登录');
        setIsModalVisible(false);
      } else {
        message.error(getErrorMsg(res));
      }
    });
  };
  return (
    <div className={styles.loginForm}>
      <ForgetPassCode  isModalVisible={isModalVisible} handleOk={handleOk} handleCancel={() => {
        setIsModalVisible(false);
      }}/>
      <div className={styles.title}>用户登录</div>
      <Form
        form={form}
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Form.Item
          name="loginAccount"
          rules={[{ required: true, message: '请输入手机号码或者邮箱!' }]}
        >
          <Input placeholder="请输入手机号码或者邮箱！" />
        </Form.Item>
        <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
          <Input type="password" placeholder="请输入密码" />
        </Form.Item>
        <Form.Item name="autoLogin">
          <div className={styles.autoLogin}>
            <div>
              <Checkbox onChange={autoLogin} /> 自动登录
            </div>
            <div style={{ cursor: 'pointer' }} onClick={forgetPassCode} className={styles.forgetPass}>忘记密码</div>
          </div>
        </Form.Item>
        <Form.Item>
          <Button loading={loginLoading} style={{ width: '100%' }} type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={loginWithMsn} className={styles.useMsnLogin} type="primary">
            使用短信验证码登录
          </Button>
        </Form.Item>
        <Form.Item>
          <div className={styles.bottomAction}>
            <div onClick={() => history.push('Register')} className={styles.goLogin}>
              <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>已有账号？</span>去注册
            </div>
            <div onClick={loginWithWechat} className={styles.wechat}>
              <img src={wechatPic} alt="" />
              使用微信登录
            </div>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
};
export default UserLogin;
